# ======================================================================
# Initial Setup for Project Analysis Workflow
# ======================================================================

# === Package Installation ===
# Uncomment and run this block *once* to install all required packages
# install.packages(c("readr", "readxl", "fs", "purrr", "stringr", "tidyr", 
#                    "dplyr", "janitor", "sf", "magrittr", "areal",
#                    "haven", "fixest", "sandwich", "PanelMatch", 
#                    "tidymodels", "modelsummary", "kableExtra", 
#                    "ggdist", "viridis", "hrbrthemes", "tictoc"))

# === Load Core Tidyverse Packages ===
library(tidyverse)   # Core packages: dplyr, ggplot2, readr, purrr, stringr, tidyr
library(cowplot)     # Combine multiple ggplot2 plots into a single figure
library(magrittr)    # Provides compound pipe operator `%<>%` for inline assignment chaining
library(readxl)      # Excel file import
library(haven)       # Import Stata `.dta` files
library(janitor)     # Data cleaning: `clean_names()`, `row_to_names()`
library(fs)          # Filesystem operations: `dir_ls()` etc.

# === Modeling and Estimation Tools ===
library(fixest)      # Fast fixed effects models, e.g. `feols()` for TWFE and beyond
library(sandwich)    # Heteroskedasticity-robust and clustered SEs, e.g. `vcovBS()`


# ======================================================================
# Load (or install) PanelMatch 2.2.0 and warn if the user has 3.x
# ======================================================================

if (!requireNamespace("PanelMatch", quietly = TRUE)) {
  message("PanelMatch not found – installing version 2.2.0 …")
  if (!requireNamespace("remotes", quietly = TRUE))
    install.packages("remotes")
  remotes::install_version("PanelMatch", version = "2.2.0",
                           repos = "https://cran.r-project.org",
                           dependencies = FALSE)
}

library(PanelMatch)   # now load whatever is installed
pm_ver <- packageVersion("PanelMatch")
message("PanelMatch version detected: ", pm_ver)

if (pm_ver >= "3.0.0") {
  cat(
    "\n",
    "*****************************************************************\n",
    "*  NOTE: This replication code requires PanelMatch 2.2.0.        *\n",
    paste0("*  You are currently running version ", as.character(pm_ver), "."),
    strrep(" ", 59 - nchar(as.character(pm_ver))), "*\n",
    "*                                                               *\n",
    "*  Please do the following, then restart R and rerun the script:*\n",
    "*                                                               *\n",
    "*      remove.packages(\"PanelMatch\")                            *\n",
    "*      remotes::install_version(\"PanelMatch\", version = \"2.2.0\") *\n",
    "*****************************************************************\n"
  )
}

# === Spatial Projection ===
library(sf)          # For spatial data when harmonizing counties 
library(tictoc)      # Used when obtaining Total projection time
library(furrr)       # Used for mapping functions with future’s parallel processing
library(areal)       # Used for areal interpolation of counties' boundaries

# === Workflow and Reporting Utilities ===
library(tidymodels)      # Framework for machine learning pipelines and pre-processing
library(modelsummary)    # Flexible model output to LaTeX/HTML/Markdown
library(kableExtra)      # Enhanced tables via `knitr::kable()`: styling, footnotes, headers

# === Visualization Enhancements ===
library(ggdist)      # For distributional plots and uncertainty intervals, e.g. `geom_pointinterval()`
library(viridis)     # Colorblind-friendly palette for consistent and interpretable color use
library(hrbrthemes)  # Clean and typography-improved ggplot2 themes (e.g., `theme_ipsum()`)
library(panelView)   # Visual diagnostics for panel data setups (e.g., treatment timing)

# === Backend Support ===
library(Rcpp)        # C++ support backend; used internally by packages like `fixest` and `modelsummary`

rm(list = ls())  # Clear workspace to avoid conflicts

# ======================================================================
# Project-Specific Scripts and Data Preparation
# ======================================================================

# === Specify Working Directory ===
# Note: Please ensure the working directory is set so that: 
# 1. the r-scripts referenced below are in a subdirectory named "code"
# 2. all .rds files are stored in a subdirectory named "data"
# 3. a subdirectory "output" that contains three subfolders: "tables", "maps", and "figures" for storing output files
# 4. Due to bootstraping, standard errors might be slightly different than those on the original manuscript's tables

# # Example path"
# setwd("/Users/fabio/Library/CloudStorage/Dropbox/HU_dropbox/projects/antomio_paper/06_replication")  # Set this to your project root directory


# === Custom Themes and Functions ===
source("code/theme_cust.R")                   # Custom ggplot2 theme (likely `theme_hanno()` or similar)
source("code/00_custom_functions.R")          # Utility functions used throughout project

# === Data Pipeline for main analyses ===
source("code/01_get_data.R")                  # Import and structure raw data sources
source("code/02_geo_project_across_time.R")   # Project geospatial data consistently across years
source("code/03_clean_data.R")                # Standard cleaning: variable naming, missingness, recoding

# === Treatment and Regression Figures ===
source("code/04_fd_analysis.R")               # First-difference regression analysis
source("code/theme_cust.R")                   # Custom ggplot2 theme (likely `theme_hanno()` or similar)
source("code/05_treatment_figs.R")               # Visualizations of treatment rollout or status
source("code/06_twfe_analysis.R")             # Two-way fixed effects regression analysis

# === PanelMatch Analyses and Robustness ===
source("code/07_fd_additional_analysis.R")    # Additional checks/robustness for FD models
source("code/07bis_coefplot_fd_figure.R")     # Creates figure 1
source("code/08_getting_matched_sets.R")      # Construction of matched sets (e.g., via PanelMatch)
source("code/09_get_covariate_balance.R")     # Covariate balance diagnostics post-matching
source("code/10_fig_improv_cov_bal_method_comp.R")  # Visual comparison of matching method performance
source("code/11_matching_pl_trends_figure.R")       # Pre-treatment trend assessment for matched units
source("code/12_getting_panel_estimates.R")   # Panel model estimation and uncertainty intervals
source("code/13_fig_histo_matched_sets.R")    # Distribution of matched set characteristics (histograms)
source("code/theme_cust.R")                   # Custom ggplot2 theme (likely `theme_hanno()` or similar)
source("code/14_fig_att_results.R")           # Creates figure 3


# === SOEP Analyses and Robustness ===
source("code/15_soep_appendix_table_c6_c7.R") # Analyses and Tables for SOEP data (Tables C6 and C7)

# === 1983 Survey Analyses ===
source("code/16_survey1983.R") # Analyses, Figures and Tables using 1983 Election Survey data (Main Text and Appendix)

# === Cross-Country Analyses ===
source("code/17_crosscountry.R") # Analyses and Figures using cross-country data (Figures E.9 and E.10)
